package com.itcoon.cloud.framework.webmvc.exception.handler;/**
 * @author Athric Yu
 * 2024/12/17
 **/

import com.itcoon.cloud.framework.ex.errorcode.CommonServiceErrorCode;
import com.itcoon.cloud.framework.webmvc.config.properties.GlobalWebConfigProperties;
import com.itcoon.cloud.framework.webmvc.response.ApiResponse;
import com.itcoon.cloud.framework.webmvc.utils.ApiResponseUtils;

import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 *
 *
 * @author Athric Yu
 * 2024/12/17
 **/
public class ConstraintViolationExceptionHandler extends ParamsExceptionHandler<ConstraintViolationException> {

    private final GlobalWebConfigProperties properties;

    public ConstraintViolationExceptionHandler(GlobalWebConfigProperties properties) {
        this.properties = properties;
    }


    @Override
    public boolean support(Exception e) {
        return e instanceof ConstraintViolationException;
    }

    @Override
    public void handle(HttpServletResponse response, ConstraintViolationException e) {
        loopLog(e);
        Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
        List<String> errMessages =  constraintViolations.stream().map(ConstraintViolation::getMessage).collect(Collectors.toList());
        ApiResponseUtils.writeJsonResponse(response, ApiResponse.error(CommonServiceErrorCode.BAD_PARAMETER.getCode(), CommonServiceErrorCode.BAD_PARAMETER.getMessage(), errMessages), properties.getResponse().getBizExceptionHttpStatus().value());
    }
}
